package com.unknowpupil.utils;

import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * @Description: 描述。</br>
 * <p>
 *
 * </p>
 * @author: <a> w10g </a>
 * @data: 2020/8/19 19:26
 * @since: 0.0.2
 */
@Component
public class SendEmailUtils {
    @Value("${spring.mail.username}")
    private String sender;

    @Resource
    private JavaMailSender javaMailSender;


    @Resource
    private FreeMarkerConfigurer configurer;


    /**
     *
     * @param model 模板参数
     * @param title 标题
     * @param templateName 模板名称
     * @param to 收件方
     * @throws Exception
     */
    public void sendMail( Map<String,Object> model,String title,String templateName,String to) throws Exception{
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //防止成为垃圾邮件，披上outlook的马甲
        mimeMessage.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869");
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        //设置发送方
        helper.setFrom(sender,"监控通知");
        //设置收件方
        helper.setTo(to);
        //读取邮件模板
        Template template = configurer.getConfiguration().getTemplate(templateName);
        String text = FreeMarkerTemplateUtils.processTemplateIntoString(template,model);
        helper.setText(text,true);
        //设置标题
        helper.setSubject(title);
        //发送邮件
        javaMailSender.send(mimeMessage);
    }


    /**
     *
     * @param model 模板参数
     * @param title 标题
     * @param templateName 模板名称
     * @param tos 收件方
     * @throws Exception
     */
    public void sendMail(Map<String,Object> model,String title,String templateName,String[] tos) throws Exception{
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //防止成为垃圾邮件，披上outlook的马甲
        mimeMessage.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869");
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        //设置发送方

        helper.setFrom(sender,"服务监控");
        //设置收件方
        helper.setTo(tos);
        //读取邮件模板
        Template template = configurer.getConfiguration().getTemplate(templateName);
        String text = FreeMarkerTemplateUtils.processTemplateIntoString(template,model);
        helper.setText(text,true);
        //设置标题
        helper.setSubject(title);
        //发送邮件
        javaMailSender.send(mimeMessage);
    }


}
